import { format, startOfMonth, endOfMonth, startOfDay, endOfDay } from 'date-fns'
// import { logError } from '@/apis/common'
import { mineApi } from '@/apis'
import { getVipUrl } from '@/apis/Promotion'
import store from '@/stores/index'
import { getPayOpenId, getWeChatCode,getMiniProgramOpenId } from '@/apis/order.js'
// #ifdef H5
import Clipboard from 'clipboard'
import Bridge from '@/plugins/JSBridge'
// #endif

const userAgent = navigator ? navigator.userAgent : false
const isInAndroidApp = !!(userAgent && userAgent.match('biXuan_android_'))
const isIniOSApp = !!(userAgent && userAgent.match('biXuan_iOS_'))

// 获取已打开的页面栈
const _getCurrentPages = function() {
  /* eslint-disable */
  return getCurrentPages()
  /* eslint-disable-end */
}

// 错误报警
export async function log(data) {
  console.log(data)
}

// 所有页面的路由
export const routePath = [
  '/pages/home/index',
  '/pagesBox/box/index',
  '/pages/share/index',
  '/pagesMember/vip/index',
  '/pages/cart/index',
  '/pagesPublic/category/index',
  '/pagesPublic/search/index',
  '/pages/mine/index',
  '/pages/login/inviteShow',
  '/pagesOther/middle/index',
  '/pagesOther/register/index',
  '/pagesOther/download/index',
  '/pagesOther/download/live',
  '/pagesDetail/box-sale/index',
  '/pagesDetail/choiceness/index',
  '/pagesDetail/commodity/index',
  '/pagesDetail/commodity/user-comment',
  '/pagesDetail/recommend/index',
  '/pagesDetail/schema/index',
  '/pagesDetail/template/index',
  '/pagesDetail/welfare/index',
  '/pagesDetail/fullcut/index',
  '/pagesMine/address/address',
  '/pagesMine/address/address-manage',
  '/pagesMine/certification/index',
  '/pagesMine/certification/bankChoose',
  '/pagesMine/certification/success',
  '/pagesMine/collection/index',
  '/pagesMine/coupon/index',
  '/pagesMine/feedback/index',
  '/pagesMine/invited/index',
  '/pagesMine/invited/myInvited',
  '/pagesMine/order/index',
  '/pagesMine/service/index',
  '/pagesMine/setting/index',
  '/pagesMine/user-info/index',
  '/pagesMine/user-info/nick',
  '/pagesMine/user-info/sign',
  '/pagesMine/user-info/other',
  '/pagesMine/wechat-card/index',
  '/pagesMine/rule/index',
  '/pagesMine/aboutus/index',
  '/pagesMine/my-red-packets/index',
  '/pagesMine/my-red-packets/unuseReward',
  '/pagesMine/my-red-packets/unusePackets',
  '/pagesMine/my-red-packets/details',
  '/pagesMine/earnings/index',
  '/pagesMine/teamGiftBag/index',
  '/pagesActivity/group-buy/index',
  '/pagesActivity/group-buy/result',
  '/pagesActivity/sale-top-ranking/index',
  '/pagesActivity/live-telecast/index',
  '/pagesActivity/lucky-rotary-table/index',
  '/pagesActivity/new-member-ship/index',
  '/pagesActivity/n-pieces/index',
  '/pagesActivity/red-packet/index',
  '/pagesActivity/sign-page/index',
  '/pagesActivity/whole-films/index',
  '/pagesActivity/zho-page/index',
  '/pagesBHS/middle/index',
  '/pagesApp/wantToBuy/index',
  '/pagesApp/wantToBuy/user',
  '/pagesMaterial/publish/index'
]
// 调整tab页面配置
export const switchTabPage = ['/pages/home/index', '/pages/coupon/index', '/pages/moments/index', '/pagesDetail/living-list/index', '/pages/mine/index']

// 跳转webview的白名单配置
export const mapWebView = [
  {
    url: 'https://preilikewap.zmaxfilm.com',
    key: 'zmaxfilm'
  },
  {
    url: 'https://chat.sobot.com',
    key: 'sobot'
  },
  {
    url: 'https://h5.bisinuolan.cn',
    key: 'h5'
  },
  {
    url: 'https://h5-uat.bisinuolan.cn',
    key: 'h5-uat'
  },
  {
    url: 'https://m.bisinuolan.cn',
    key: 'm'
  },
  {
    url: 'https://m-uat.bisinuolan.cn',
    key: 'm-uat'
  },
  // {
  //   url: 'http://bx-co-sh-uat-appcommission.bsnlcloud.cn',
  //   key: 'commission-sh-uat'
  // },
  // {
  //   url: 'http://bx-co-uat-appcommission.bsnlcloud.cn',
  //   key: 'commission-uat'
  // },
  // {
  //   url: 'https://bx-co-uat-sh-appcommission.bsnlcloud.cn',
  //   key: 'commission-sh-uat'
  // },
  {
    url: 'http://bx-uat-appgateway.bsnlco.com',
    key: 'commission-uat'
  },
  {
    url: 'http://bx-uat-app-h5.bsnlco.com',
    key: 'commission-h5-uat'
  },
  {
    url: 'http://192.168.5.105:9528',
    key: 'wqj'
  },
  {
    url: 'https://mp.weixin.qq.com/s',
    key: 'weixin'
  },
  {
    url: 'http://mp.weixin.qq.com/s',
    key: 'weixin'
  },
  {
    url: 'https://contract01.gongmall.com',
    key: 'gongmall'
  },
  {
    url: 'https://contract-qa01.gongmall.com',
    key: 'gongmall-uat'
  }
]

// 判断是否在APP内
export function inApp() {
  return isInAndroidApp || isIniOSApp
}

/*
data数据结构
{
  type: 'page', // page[页面跳转]、share[分享]
  params: {
    pageName: 'goods', // 页面名称
    goodsId: 123 //
  }
}
{
  type: 'share', // page[页面跳转]、share[分享]
  params: {
    imgUrl: '',
    title: '',
    desc: '',
    url: ''
  }
}
 */
export function callApp(data) {
  try {
    if (isIniOSApp) {
      return JSON.parse(window.webkit.messageHandlers.biXuanApp.postMessage(JSON.stringify(data)))
    } else if (isInAndroidApp) {
      return JSON.parse(window.APPCALL.biXuanApp(JSON.stringify(data)))
    } else {
      return false
    }
  } catch (e) {
    console.log(e)
    return false
  }
}

/*
 * 函数：下载
 * author: wangzm
 * 参数：list：要下载的文件列表, config: 配置
 * 返回：void
 */
export function downloadFile(list = [], config = {}) {
  const option = {
    fileKey: '', // 有配置的时候，list的item[fileKey]，为空时直接取item
    fileType: 'Image', // 文件类型：Image、Video
    callback: () => {},
    emptyMsg: '下载包暂无内容', // 无文件可下载时提示
    ...config
  }
  const totalNum = list.length
  let successNum = 0
  let failNum = 0
  if (totalNum) {
    uni.showLoading({ title: '下载中...' })
  } else {
    uni.showToast({ title: option.emptyMsg, icon: 'none' })
    return
  }
  list.map(item => {
    uni.downloadFile({
      url: option.fileKey ? item[option.fileKey] : item,
      success: res => {
        uni[`save${option.fileType}ToPhotosAlbum`]({
          // uni.saveVideoToPhotosAlbum
          filePath: res.tempFilePath,
          success: () => {
            successNum++
            if (totalNum === successNum + failNum) {
              uni.hideLoading()
              option.callback(successNum, failNum)
            }
          },
          fail: e => {
            failNum++
            uni.hideLoading()
            option.callback(successNum, failNum)
          }
        })
      },
      fail: e => {
        failNum++
        uni.hideLoading()
        option.callback(successNum, failNum)
      }
    })
  })
}

/*
 * 函数：支付
 * author: wangzm
 * 参数：config：支付参数, type: 支付类型【wxpay：微信小程序支付】
 * 返回：void
 */
export function toPay(config, type = 'wxpay') {
  const wxPayInfo = config.wxPayInfo.wxJSAPIPayInfoResponse
  if (type === 'wxpay') {
    uni.requestPayment({
      provider: 'wxpay',
      signType: wxPayInfo.signType || 'MD5',
      timeStamp: wxPayInfo.timeStamp,
      nonceStr: wxPayInfo.nonceStr,
      package: wxPayInfo.package,
      paySign: wxPayInfo.paySign,
      success: res => {
        if (config && typeof config.success === 'function') {
          config.success(res)
        }
      },
      fail: res => {
        if (config && typeof config.fail === 'function') {
          config.fail(res)
        }
      }
    })
  }
}
// 公众号支付获取openId
export async function requestOpenId() {
  if (!Bridge.isInWeChat) return
  try {
    if (store && store.state && store.state.userInfo && store.state.userInfo.openId) {
      return
    }
      console.log(location.href);
      const code = getQueryString('code', location.href);
      console.log(code);
      if (!code) {
        getWeChatCode()
        return
      }
      const res = await getPayOpenId({ code: code })
      if (res.success) {
        store.dispatch('SET_USER_INFO', {
          openId: res.data
        })
      }
    return
  } catch (e) {
    console.log(e)
  }
}
//获取微信小程序openid
export async function getMiniOpenId() {
// #ifdef MP-WEIXIN
  if (store && store.state && store.state.userInfo && store.state.userInfo.openId) {
    return
  }
  wx.login({
    success:(res)=>{
      if (res.code) {
        getMiniProgramOpenId({jsCode:res.code}).then(res=>{
          store.dispatch('SET_USER_INFO', {
            openId: res.data
          })
        });
      }
    }
  });
// #endif
}
/**
 * 获取当前页的链接及其参数
 */
export function getCurrentPageUrl() {
  // #ifdef H5
  return window.location.href
  // #endif

  // #ifndef H5
  let pages = _getCurrentPages()
  if (pages.length === 0) {
    return ''
  }
  let current = pages[pages.length - 1]
  let route = current.route
  let query = current.options
  return formatUrlParam(route, query)
  // #endif
}

/*
 * 函数：拨打电话
 * author: Mole
 * 参数：phone: 电话号码、option：其它配置
 * 返回：无
 */
export function callPhone(phone = '', option = {}) {
  const config = {
    phoneNumber: phone,
    success: () => {},
    fail: () => {},
    complete: () => {},
    ...option
  }
  if (phone) {
    uni.makePhoneCall(config)
  }
}

/*
 * 函数：分享 两个函数
 * author: wangzm
 * 参数：option：支付参数 type: 分享类型---mp-weixin[微信小程序]
 * 返回：分享完整配置
 */

export function createSharePathUrl(option = {},get_H5=false) {
  let pages = _getCurrentPages()
  let current = pages[pages.length - 1]
  let route = current.route
  let query = current.options || (current.$mp ? current.$mp.query : {})
  // console.log(current.options, current.$mp, current.$mp.query, 6666666666)
  query.isShare = true // 带上分享
  delete query.token
  delete query.user_token
  let optionPath = option.share_url
  if (optionPath) {
    if (optionPath.indexOf('isShare=') > 0) {
    } else if (optionPath.indexOf('?') > 0) {
      optionPath += `&isShare=true`
    } else {
      optionPath += `?isShare=true`
    }
  }
  if (store && store.state && store.state.userInfo && store.state.userInfo.invite_code) {
    query.share_code = store.state.userInfo.invite_code // 分享带上邀请码
    if (optionPath) {
      if (optionPath.indexOf('?') > 0) {
        optionPath += `&share_code=${query.share_code}`
      } else {
        optionPath += `?share_code=${query.share_code}`
      }
    }
  }
  let path = optionPath || `/${formatUrlParam(route, query)}` // 页面 path ，必须是以 / 开头的完整路径。
  // #ifdef H5
  if (option.link) {
    return location.origin + `/pages/share/index?path=${encodeURIComponent(path)}`
  }
  // #endif
	if (get_H5) {
	  return process.env.VUE_APP_PRE_URL + `/pages/share/index?path=${encodeURIComponent(path)}`
	}
  return path
}

export function queryShareOption(res, option = {}) {
  const path = createSharePathUrl(option)
  const defaultOption = {
    share_title: '碧选-品牌社交电商', // 分享标题
    share_content: '代理终身免费打卡领面膜 年省16000+', // 分享描述
    share_icon: `https://oss.bisinuolan.cn/default-1568795237944-58042a75ac66485491c3f328818bd070.png`, // 分享图标，路径可以是本地文件路径、代码包文件路径或者网络图片路径、支持PNG及JPG。显示图片长宽比是 5:4
    share_image: `${process.env.VUE_APP_IMAGE_ASSET}/images/share-default.png` // 分享图片，路径可以是本地文件路径、代码包文件路径或者网络图片路径、支持PNG及JPG。显示图片长宽比是 5:4
  }
  const resultOption = {
    ...defaultOption,
    ...option,
    share_url: `/pages/share/index?path=${encodeURIComponent(path)}` // 页面 path
  }
  // #ifdef MP-WEIXIN
  return {
    ...resultOption,
    title: resultOption.share_title,
    imageUrl: resultOption.share_image || resultOption.share_icon,
    path: resultOption.share_url
  }
  // #endif

  // #ifdef H5
  return {
    ...resultOption,
    share_url: location.origin + resultOption.share_url
  }
  // #endif
  return resultOption
}

/*
 * 函数：获取页面参数
 * author: wangzm
 * 参数：option：页面option, name: 参数名称
 * 返回：参数值
 */
export function queryPageParam(option, name) {
  if (option) {
    if (option[name]) {
      return option[name]
    } else if (option.scene) {
      const scene = decodeURIComponent(option.scene)
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
      var r = scene.match(reg)
      if (r != null) return unescape(r[2])
      return null
    }
  }

  return null
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  var timeout, result

  var debounced = function() {
    var context = this
    var args = arguments

    if (timeout) clearTimeout(timeout)
    if (immediate) {
      // 如果已经执行过，不再执行
      var callNow = !timeout
      timeout = setTimeout(function() {
        timeout = null
      }, wait)
      if (callNow) result = func.apply(context, args)
    } else {
      timeout = setTimeout(function() {
        result = func.apply(context, args)
      }, wait)
    }
    return result
  }

  debounced.cancel = function() {
    clearTimeout(timeout)
    timeout = null
  }

  return debounced
}

// 判断是否含有class
export function hasClass(el, className) {
  const reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
  return reg.test(el.className)
}

// 添加class
export function addClass(el, className) {
  if (hasClass(el, className)) {
    return
  }

  const newClass = el.className.split(' ')
  newClass.push(className)
  el.className = newClass.join(' ')
}
export function getData(el, name, val) {
  const prefix = 'data-'
  if (val) {
    return el.setAttribute(prefix + name, val)
  }
  return el.getAttribute(prefix + name)
}
/**
 * @Author: wjk
 * @Date: 2019-11-20 10:36:56
 * @LastEditors: wjk
 * @description: 获取url中某个参数的值
 * @param {name}: key值
 * @param {url}: 地址 默认window.location.search
 * @return: value值
 */
export function getQueryString(name, url) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  if (url) {
    url = url.substring(url.indexOf('?'))
  } else {
    url = window.location.search
  }
  var r = url.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}
/**
 * @Author: wjk
 * @Date: 2019-11-20 10:38:23
 * @description: 更新url中某个参数的值
 * @param {uri}: url地址
 * @param {key值}: url中需要修改的key
 * @param {value值}: 需要修改的key对应的value值
 * @return: 返回新的url
 */

export function updateQueryStringParameter(uri, key, value) {
  if (!value) {
    return uri
  }
  var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i')
  var separator = uri.indexOf('?') !== -1 ? '&' : '?'
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + '=' + value + '$2')
  } else {
    return uri + separator + key + '=' + value
  }
}

//获取今日开始、结束时间
export function getTodayDate() {
  var today = []
  var todayDate = new Date()
  var aa = format(startOfDay(todayDate), 'yyyy-MM-dd HH:mm:ss')
  var bb = format(endOfDay(todayDate), 'yyyy-MM-dd HH:mm:ss')
  today.push(aa)
  today.push(bb)
  return today
}

//获取昨日开始、结束时间
export function getYesterdayDate() {
  var yesterdayArr = []
  var today = new Date()
  var yesterday = new Date(today.setTime(today.getTime() - 24 * 60 * 60 * 1000))
  var aa = format(startOfDay(yesterday), 'yyyy-MM-dd HH:mm:ss')
  var bb = format(endOfDay(yesterday), 'yyyy-MM-dd HH:mm:ss')
  yesterdayArr.push(aa)
  yesterdayArr.push(bb)
  return yesterdayArr
}

//获取本月开始、结束时间
export function getCurrentMonthDate() {
  let month = []
  //获取当前时间
  const today = new Date()
  const startMonth = startOfMonth(today)
  const aa = format(startMonth, 'yyyy-MM-dd HH:mm:ss')
  month.push(aa)
  const endMonth = endOfMonth(today)
  const bb = format(endMonth, 'yyyy-MM-dd HH:mm:ss')
  month.push(bb)
  return month
}

// 获取上月开始、结束时间
export function getLastMonthDate() {
  let month = []
  const date = new Date()
  var y = date.getFullYear()
  var m = date.getMonth()
  if (m === 0) {
    y = y - 1
    m = 12
  }
  var dateTime = y + '/' + m + '/01'
  const startMonth = startOfMonth(new Date(dateTime))
  const aa = format(startMonth, 'yyyy-MM-dd HH:mm:ss')
  month.push(aa)
  const endMonth = endOfMonth(new Date(dateTime))
  const bb = format(endMonth, 'yyyy-MM-dd HH:mm:ss')
  month.push(bb)
  return month
}

// ------------------ filters ------------------
/*
 * 函数：时间格式化
 * author: wangzm
 * 参数：date[null、undefined、''、Date、时间戳]、pattern：格式[字符串，非必填]
 * 返回：格式化的时间字符串
 * 提示：IOS如果返回的是字符串最好不要使用，很多格式没办法转
 */
export function formatDate(date, pattern = 'yyyy-MM-dd HH:mm:ss') {
  if (date) {
    let originDate="";
    if(typeof date === 'number'){
      if(date.toString().length===13){
        originDate=new Date(date);
      }else{
        originDate=new Date(date*1000);
      }
    }else{
      originDate=new Date(date);
    }
    const str = format(originDate, pattern)
    return str
  }
  return '-'
}

//未*1000时间戳格式化
export function formatTimes(date, pattern = 'yyyy-MM-dd HH:mm:ss') {
  if (date) {
    let originDate = new Date(date * 1000);
    const str = format(originDate, pattern)
    return str
  }
  return '-'
}
/*
 * 函数：金额格式化
 * author: wangzm
 * 参数：money[null、undefined、''、Number、数字字符串]、dot：是否每三位逗号隔开、digit：保留小数的位数
 * 返回：格式化的金额字符串
 */
export function formatMoney(money, digit = 2, dot = false) {
  if (!money) return '0.00'
  var mm = money.toString()
  var index = mm.indexOf('.')
  if (index !== -1) {
    mm = mm.substring(0, digit + index + 1)
  } else {
    mm = mm.substring(0)
  }
  if (!dot) {
    return parseFloat(mm).toFixed(digit)
  } else {
    var moneyArray = parseFloat(mm)
      .toFixed(digit)
      .split('.')
    var num = moneyArray[0]
    var result = ''
    while (num.length > 3) {
      result = ',' + num.slice(-3) + result
      num = num.slice(0, num.length - 3)
    }
    if (num) {
      result = num + result
    }
    if (moneyArray.length > 1) {
      result += '.' + moneyArray[1]
    }
    return result
  }
}

/*
 * 函数：数字格式化成万
 * author: wangzm
 * 参数：num[null、undefined、''、Number]、digit：保留小数的位数、formatZero：是否去除末尾0
 * 返回：格式化的大额数字字符串
 */
export function formatNumber(num, digit = 2, formatZero = false) {
  let result = 0
  if (num > 99999) {
    digit = 1
  }
  if (num > 9999) {
    if (formatZero) {
      let multiple = 1
      for (let i = 0; i < digit; i++) {
        multiple *= 10
      }
      result = Math.floor((num / 10000) * multiple) / multiple + 'w'
    } else {
      result = (num / 10000).toFixed(digit) + '万'
    }
  } else if (num > 0) {
    result = num
  }

  return result
}

/*
 * 函数：数字格式化成万
 * author: wangzm
 * 参数：num[null、undefined、''、Number]、digit：保留小数的位数
 * 返回：格式化的大额数字字符串
 */
export function formatNumberPlus(num, max = 999) {
  let result = 0
  if (num > max) {
    result = max + '+'
  } else if (num > 0) {
    result = num
  }

  return result
}

export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return ''
  }

  if ((time + '').length === 10) {
    time = +time * 1000
  }

  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    date = new Date(parseInt(time))
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}
/* 数字 格式化*/
export function nFormatter(num, digits) {
  const si = [
    { value: 1e18, symbol: 'E' },
    { value: 1e15, symbol: 'P' },
    { value: 1e12, symbol: 'T' },
    { value: 1e9, symbol: 'G' },
    { value: 1e6, symbol: 'M' },
    { value: 1e3, symbol: 'k' }
  ]
  for (let i = 0; i < si.length; i++) {
    if (num >= si[i].value) {
      return (num / si[i].value + 0.1).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
    }
  }
  return num.toString()
}

/**
 * 拼接参数到 链接后面
 * @param String url 要拼接的地址
 * @param Object query 要拼接的参数
 */
export function formatUrlParam(url = '', query = {}) {
  let newUrl = url
  let flag = false
  const keyArr = Object.keys(query)
  keyArr.forEach(key => {
    if (query[key] !== undefined && query[key] !== null && query[key] !== '') {
      const val = encodeURIComponent(query[key])
      newUrl += `${flag ? '&' : '?'}${key}=${val}`
      flag = true
    }
  })
  return newUrl

  /* let newUrl = url + '?'
  const keyArr = Object.keys(query)
  const len = keyArr.length
  if (url && len > 0) {
    keyArr.forEach((key, index) => {
      if (query[key] !== undefined) {
        const val = encodeURIComponent(query[key])
        newUrl += `${key}=${val}${len - 1 > index ? '&' : ''}`
      }
    })
  }
  return newUrl */
}
/**
 * url参数转json对象
 * @param String url 拼接解析的地址参数
 * @return Object 参数对象
 */
export function paramsToObj(url = '') {
  const temp = url.split('?')
  const params = temp[temp.length - 1]
  const tArray = params.split('&')
  const obj = {}
  let t = []
  tArray.map(i => {
    t = i.split('=')
    obj[t[0]] = t[1]
  })

  return obj
}

export const filters = {
  formatDate,
  formatMoney,
  formatNumber,
  parseTime,
  formatTime,
  nFormatter,
  formatNumberPlus,
  formatTimes
}

/**
 * @Author: wjk
 * @Date: 2019-11-20 10:38:23
 * @description: 检验数量入参
 * @param {val}: 入参
 * @return: 校验结果
 */
export function inputCheckNumber(val) {
  let result = true
  if (isNaN(val)) {
    uni.showToast({
      title: '请输入数字',
      icon: 'none',
      duration: 2 * 1000
    })
    result = false
  } else if (val <= 0) {
    uni.showToast({
      title: '数量不能小于1哦',
      icon: 'none',
      duration: 2 * 1000
    })
    result = false
  }
  return result
}

/**
 * 复制文本
 * @param {} options {data: '要复制的文本',success:()=>{},fail:()=>{},complete:()=>}
 */
export function setClipboardData(options) {
  const defaultConfig = {
    data: '',
    success: () => {},
    fail: () => {},
    complete: () => {}
  }
  const config = Object.assign({}, defaultConfig, options)
  // #ifdef H5
  if (Bridge.isInApp) {
    Bridge.callHandler({
      type: 'copyInfo',
      data: config.data
    })
  } else {
    let clipboard = new Clipboard('.null', {
      text: () => config.data
    })

    clipboard.on('success', function(e) {
      uni.showToast({
        title: '复制成功',
        icon: 'none'
      })
      config.success && config.success(e)
      config.complete && config.complete(e)
      clipboard.off('error')
      clipboard.off('success')
      clipboard.destroy()
    })
    clipboard.on('error', function(e) {
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      })
      config.fail && config.fail(e)
      config.complete && config.complete(e)
      clipboard.off('error')
      clipboard.off('success')
      clipboard.destroy()
    })
    clipboard.onClick(window.event)
  }
  // #endif

  // #ifndef H5
  uni.setClipboardData(config)
  // #endif
}

/**
 * 获取剪切板文本
 */
export function getClipboardData(callback) {
  let result = ''
  // #ifdef H5
  if (window.clipboardData) {
    result = window.clipboardData.getData('Text')
  } else if (window.netscape) {
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect')
    var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard)
    var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable)
    if (clip && trans) {
      trans.addDataFlavor('text/unicode')
      clip.getData(trans, clip.kGlobalClipboard)
      var str = new Object()
      var len = new Object()
      try {
        trans.getTransferData('text/unicode', str, len)
      } catch (error) {
        console.log(error)
      }
      if (str) {
        if (Components.interfaces.nsISupportsWString) str = str.value.QueryInterface(Components.interfaces.nsISupportsWString)
        else if (Components.interfaces.nsISupportsString) str = str.value.QueryInterface(Components.interfaces.nsISupportsString)
        else str = null
      }
      if (str) {
        result = str.data.substring(0, len.value / 2)
      }
    }
  }

  if (callback && typeof callback === 'function') {
    callback(result)
  }
  // #endif

  // #ifndef H5
  uni.getClipboardData({
    success: res => {
      if (callback && typeof callback === 'function') {
        callback(res.data)
      }
    }
  })
  // #endif
}

/**
 * 节流
 */
export function throttle(func, delay) {
  var timer = null
  var startTime = Date.now()
  return function() {
    var curTime = Date.now()
    var remaining = delay - (curTime - startTime)
    var context = this
    var args = arguments
    clearTimeout(timer)
    if (remaining <= 0) {
      func.apply(context, args)
      startTime = Date.now()
    } else {
      timer = setTimeout(func, remaining)
    }
  }
}

//配置中心
export const appConfig = async () => {
  //获取版本号
  const getVision = await getVipUrl()
  // console.log(getVision.appconfig_version)
  //取本地版本号
  const version = uni.getStorageSync('__app_config_vision__')
  if (getVision.appconfig_version) {
    //判断获取的版本号和本地的版本号有没有变化
    if (getVision.appconfig_version !== version) {
      uni.setStorage({ key: '__app_config_vision__', data: getVision.appconfig_version })
      const res = await mineApi.getConfigCenter({ acmVersion: getVision.appconfig_version })
      uni.setStorage({
        key: '__app_config_info__',
        data: res.data
      })
    }
  }
}

// 数据分割
export const arraySplit = function(array, size) {
  let [start, end, result] = [null, null, []]
  for (let i = 0; i < Math.ceil(array.length / size); i++) {
    start = i * size
    end = start + size
    result.push(array.slice(start, end))
  }
  return result
}

// 深度克隆
export function deepClone (obj) {
	// 对常见的“非”值，直接返回原来值
	if([null, undefined, NaN, false].includes(obj)) return obj;
    if(typeof obj !== "object" && typeof obj !== 'function') {
		//原始类型直接返回
        return obj;
    }
    var o = isArray(obj) ? [] : {};
    for(let i in obj) {
        if(obj.hasOwnProperty(i)){
            o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
        }
    }
    return o;
}